# -*- coding: utf-8 -*-
__author__ = 'BuddyHolly'

import os
import shutil

from flask import render_template, flash, g
from pptx import Presentation
from functools import wraps


# 验证信息是否为数字
def allowed_text_num(text):
    return text.isdigit()


# 验证文件是否为pptx后缀
def allowed_file_ppt(file_name):
    return '.' in file_name and \
           file_name.rsplit('.', 1)[1] in ['pptx']


# 验证文件是否为png后缀
def allowed_file_png(file_name):
    return '.' in file_name and \
           file_name.rsplit('.', 1)[1] in ['png']


# 验证文件是否为jpg，jpeg，png后缀
def allowed_file_img(file_name):
    return '.' in file_name and \
           file_name.rsplit('.', 1)[1] in ['jpg', 'jpeg', 'png']


# 验证两个PPT文件内含Slide数目是否相同
def allowed_page_num(file_info):
    prs1 = Presentation(file_info['ppt1_path_name'])
    prs2 = Presentation(file_info['ppt2_path_name'])

    if prs1.slides.__len__() >= file_info['ppt1_page'] and prs2.slides.__len__() >= file_info['ppt2_page']:
        return True
    else:
        return False


# 异常处理装饰函数
# 截取所有异常刷新网页，删除所有临时文件
def error_decorator(fun):
    @wraps(fun)
    def wrapper(*args, **kwargs):
        try:
            try_result = fun(*args, **kwargs)
            return try_result
        except KeyError as e:
            error_warning = {
                'error_warning': 'A key error has occurred.'}
            for filename in g.file_list:
                os.remove(filename)
            for pathname in g.path_list:
                shutil.rmtree(pathname)
            flash("请上传常规文件后使用！")
            return render_template(g.url)
        except TypeError as e:
            error_warning = {
                'error_warning': 'A type error has occurred.'}
            for filename in g.file_list:
                os.remove(filename)
            for pathname in g.path_list:
                shutil.rmtree(pathname)
            flash("请上传常规文件后使用！")
            return render_template(g.url)
        except IOError as e:
            error_warning = {
                'error_warning': 'A IO error has occurred.'}
            for filename in g.file_list:
                os.remove(filename)
            for pathname in g.path_list:
                shutil.rmtree(pathname)
            flash("请上传常规文件后使用！")
            return render_template(g.url)
        except Exception as e:
            error_warning = {'error_warning': repr(e)}
            for filename in g.file_list:
                os.remove(filename)
            for pathname in g.path_list:
                shutil.rmtree(pathname)
            flash("请上传常规文件后使用！")
            return render_template(g.url)

    return wrapper
